<template>
    <div>
        <div class="activity-right" @click="hideSel($event)" style="padding-top:20px;">
            <h3>编辑商品</h3>
            <el-form ref="form" :rules="rules" :model="form" label-width="120px">
                <div class="form">
                    <section class="formLeft">
                        <el-form-item label="是否为爆款:">
                            <el-checkbox @change="hotSaleChange" v-model="hotSaleStatus">{{hotSaleStatus ? '是': '否'}}</el-checkbox>
                        </el-form-item>
                        <el-form-item label="爆款开始时间:" v-if="hotSaleStatus">
                            <el-date-picker v-model="form.presaleTime" type="datetime"  placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="商品名称:" prop="goodsName">
                            <el-input style="width:400px" v-model="form.goodsName" type="text"  placeholder="请输入商品名称" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="商品品牌:" prop="brandArray">
                            <el-select style="width:400px" filterable v-model="form.brandId" placeholder="选择品牌">
                                <el-option v-for="item in brandArray" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="活动专场:" prop="activityArray">
                            <el-select style="width:400px" filterable v-model="form.activityId" @change="getActivity" placeholder="选择活动">
                                <el-option v-for="item in activityArr" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="form.activityId != null && form.activityId" label="活动状态:" prop="activityStatus">
                            <template>{{activityStatus == 0 ? '展示' : (activityStatus == 1 ? '售卖中':(activityStatus == 2 ? '结束' :''))}}</template>
                        </el-form-item>
                        <el-form-item label="商品介绍:" prop="goodsDesc">
                            <el-input type='textarea' :rows="5" style="width:400px" v-model="form.goodsDesc"></el-input>
                        </el-form-item>
                        <el-form-item label="商品卖点:" >
                            <el-input type='textarea' :rows="5" style="width:400px" v-model="form.usp" :maxlength="50" placeholder="商品卖点50个字符以内"></el-input>
                        </el-form-item>
                        <el-form-item label="商品编号:" prop="goodsCode">
                            <el-input style="width:400px" v-model="form.goodsCode" type="text" placeholder="请输入商品编号" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="选择款数:" class="must">
                            <el-select v-model="goodsItemCountVal" disabled @change="goodsItemCountChange" placeholder="请选择">
                                <el-option
                                    v-for="item in goodsItemCount"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="排序:" prop="sort">
                            <el-input style="width:400px" v-model="form.sort" type="text" placeholder="1开始为最小" clearable></el-input>
                        </el-form-item>
                    </section>
                </div>
                <div id="box">
                    <div class='addGoods-1' v-for='(item,idx) in paramList' :key="item.goodsId">
                        <section>
                            <ul>
                                <li>
                                    <el-form-item label="商品状态:" >
                                        <el-switch v-model="item.soldoutStatus" :key="item.goodsId"></el-switch>
                                    </el-form-item>
                                    <section class="setPrice">
                                        <el-form-item label="商品原价:">
                                            <el-input v-model="item.goodsPrice" @blur="setOrignailChange(idx,$event)" :data-idx="idx" type="text" placeholder="请输入商品原价" clearable></el-input>
                                        </el-form-item>
                                        <el-form-item label="商品折扣率:">
                                            <el-input :disabled="true" v-model="item.discountRate" @blur="setOrignailChange(idx,$event)" :data-idx="idx" type="text" placeholder="请输入折扣率 (0-10之间的整数或一位小数)"> </el-input>
                                        </el-form-item>
                                        <el-form-item label="商品折扣价:">
                                            <el-input v-model="item.discountPrice" @blur="setChangeDiscountPrice(idx,$event)" :data-idx="idx" type="text" placeholder="请输入商品折扣价" ></el-input>
                                        </el-form-item>
                                        <el-form-item label="会员折扣率:">
                                            <el-input :disabled="true" v-model="item.memberRate" @blur="setChangeMemberRate(idx,$event)" :data-idx="idx" type="text" placeholder="请输入商品折扣价" ></el-input>
                                        </el-form-item>
                                        <el-form-item label="会员折扣价:">
                                            <el-input v-model="item.memberPrice" @blur="setChangeMemberPrice(idx,$event)" type="text" placeholder="请输入商品折扣价" clearable></el-input>
                                        </el-form-item>
                                    </section>
                                    <el-form-item label="商品规格:" prop="goodsColor">
                                        <el-input style="width:300px" v-model="item.goodsColor" type="text" placeholder="请输入商品颜色" clearable></el-input>
                                    </el-form-item>
                                    <el-form-item label="商品SKU:" prop="goodsSku">
                                        <el-input style="width:300px" v-if="!item.checked"  v-model="item.goodsSku" type="text" placeholder="请输入商品SKU码，sku码唯一" clearable></el-input>
                                        <el-input style="width:300px" v-else disabled v-model="item.goodsSku" type="text" placeholder="setEmpty" clearable></el-input>
                                        <el-checkbox style="margin-left:30px;" @change="handleChange(item)"  v-model="item.checked">置空SKU</el-checkbox>
                                    </el-form-item>
                                    <el-form-item label="商品库存:" prop="stock">
                                        <ul class='stock'>
                                            <li  :key='item.id' v-for="item in item.goodsStock">
                                                <el-input style="width:130px;" v-model="item.specsName" type="text" placeholder="尺码" clearable></el-input>
                                                :
                                                <el-input style="width:80px;" v-model="item.stockNum" type="text" placeholder="数量" clearable></el-input>
                                                商品条码
                                                :
                                                <el-input style="width:200px;" v-model="item.barCode" type="text" placeholder="商品条码必填" clearable></el-input>
                                            </li>
                                        </ul>
                                        <div class="addSize" style="margin:5px">
                                            <el-button style="float:left" type="primary" @click="addgoodsSize(idx)">新增</el-button>
                                            <el-button style="float:left" type="primary" @click="delgoodsSize(idx)">删除</el-button>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="商品轮播:" class="uploadWrap " v-loading="uploadLoading">
                                        <draggable v-model="item.goodsImageUrl">
                                            <transition-group>
                                                <div class="prevImg" :key="index" v-for="(item1,index) in item.goodsImageUrl" v-if="item.goodsImageUrl.length > 0">
                                                    <img width="200" :src="item1" alt="" />
                                                    <i class="el-icon-error" @click="deleteImgList(item,index)"></i>
                                                </div>
                                            </transition-group>
                                        </draggable>
                                        <template v-if="item.goodsImageUrl.length < 9">
                                            <div class="upload">
                                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" multiple @change="upload(idx,$event)" />
                                                <i class="el-icon-plus"></i>
                                            </div>
                                        </template>
                                        <p class="red">
                                            <small>最多可选择9张(第一张图片为商品封面图)</small>
                                        </p>
                                        <p class="red">
                                            <small>建议尺寸：图片尺寸小于400KB</small>
                                        </p>
                                    </el-form-item>
                                    <!-- <section class="addColor">
                                        <el-button type="primary" v-if="idx === paramList.length - 1"  @click="addgoodsItem('other')">新增规格</el-button>
                                        <el-button type="primary" @click="delColor(idx)">删除</el-button>
                                    </section> -->
                                </li>
                            </ul>
                        </section>
                    </div>
                </div>

            </el-form>
            <section class="submit">
                <el-button type="primary" @click="submit">确定</el-button>
                <el-button type="primary" style="margin-left:10px" @click="$router.go(-1)">返回</el-button>
            </section>
        </div>
    </div>
</template>
<script>
    import draggable from "vuedraggable";
    import {
        getProducts,
        addGoods,
        getGoodsDetailsNew,
        updateGoods,
        updateGoodsStatus,
        getQiniuToken,
        qiniuBaseUrl,
        getCategory,
        getTagByStoreNo,
        getBrand,
        allActivityList,
        getActivityDetail,
        addMultiGoods,
        getGoodsByRelation,
        updateRelationGoods
    } from "../../data/postData";
export default {
    components: {
        draggable
    },
    data() {
        return {
            user: JSON.parse(localStorage.getItem("ddaigoUser")),
            getTagByStoreNo: null,
            form: {
                goodsName: "",
                goodsPrice: "",
                storeNo: "",
                categoryId: "",
                goodsPic: "",
                soldout: "",
                brandId: "",
                goodsDesc: "",
                activityId: "",
                purchaseCost: "0",
                storePrice: "0",
                discountPrice: "",
                discountRate: "",
                memberPrice: "",
                memberRate: 9,
                goodsCode:'',
                commonGoodsImg:[],
                sort:'1',
                relation:'',
                usp:''
            },
            checked: false,
            hotSaleStatus: false, // 是否为爆款
            dataForm: null,
            activityStatus: "",
            activityArr: [],
            status: true,
            disabled: false,
            addGoodsVal: null,
            paramList: [],
            paramListCopy: [],
            brandArray: [],
            isShow1: false,
            goodsItemCount: [], // 商品款数数组
            goodsItemCountVal:'',// 商品款数值
            commonImgUploadLoading:false,// 副图片Loading
            soltArray: [
                {
                    value: "0",
                    label: "上架"
                },
                {
                    value: "1",
                    label: "下架"
                }
            ],
            categoryId: "",
            goodsItem: [],
            selGoodItemVal: [],
            isShowGoodsItem: false,
            goodsItem1: [],
            goodsItem2: [],
            goodsItem3: [],
            textarea: "",
            discount: false,
            coverUploadLoading: false,
            uploadLoading: false,
            rules: {
                goodsName: [{required: true, message: "请输入商品名称", trigger: "blur"}],
                goodsPrice: [{required: true, message: "请输入商品原价", trigger: "blur"}],
                goodsCode:[{required: true, message: "请输入商品编号", trigger: "blur"}],
                discountRate: [{ required: true, message: "请输入商品折扣价", trigger: "blur"},
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d(\.\d)?$/.test(value)) {
                                callback(
                                    new Error("正确输入折扣率：例'9'或'9.5'")
                                );
                                value = "";
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                memberRate: [{ required: true, message: "请输入会员折扣价", trigger: "blur"},
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d(\.\d)?$/.test(value)) {
                                callback(
                                    new Error("正确输入折扣率：例'9'或'9.5'")
                                );
                                value = "";
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                soldout: [{required: true, message: "请选择商品状态", trigger: "blur"}],
                memberPrice: [
                    {
                        required: true,
                        message: "请选择会员折扣价",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d+(\.\d(\d)?)?$/.test(value)) {
                                callback(
                                    new Error(
                                        "正确输入会员折扣价：保留两位小数"
                                    )
                                );
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                category: [
                    {
                        required: true,
                        message: "请选择商品类目",
                        trigger: "blur"
                    }
                ],
                brandArray: [
                    {
                        required: true,
                        message: "请选择商品品牌",
                        trigger: "blur"
                    }
                ],
                activityArray: [
                    {
                        required: true,
                        message: "请选择活动专场",
                        trigger: "blur"
                    }
                ],
                storePrice: [
                    { required: true, message: "请输入平台价", trigger: "blur" }
                ],
                discountPrice: [
                    {
                        required: true,
                        message: "请输入折扣价",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d+(\.\d(\d)?)?$/.test(value)) {
                                callback(
                                    new Error("正确输入折扣价：保留两位小数")
                                );
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                sort: [
                    {
                        required: true,
                        message: "请输入排序",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d+$/.test(+value) || +value < 1) {
                                callback(
                                    new Error("正确输入折扣率：例1、2、3")
                                );
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
            }
        };
    },
    mounted() {
        // 设置款数
        // for (let i = 1; i <= 20; i++) {
        //     this.goodsItemCount.push({
        //         label: i,
        //         value: i
        //     })
        // }
        // 获取三级列表的第一级
        // this.$fetch.get(getCategory + "?categoryId=0").then(res => {
        //     this.goodsItem1 = res.data;
        // });
        this.getGoodsByRelation()
        var params = {
            data: {}
        };
        this.$fetch
            .post(getBrand, params)
            .then(res => {
                res.data.forEach((item, i) => {
                    this.brandArray.push({
                        value: item.id,
                        label: item.name
                    });
                });
            })
            .catch(err => {});

        var params1 = {
            data: {
                storeNo: this.user.storeNo
            }
        };
        this.$fetch
            .post(allActivityList, params1)
            .then(res => {
                var activity = [];
                res.data.forEach((val, i) => {
                    activity.push({ value: val.id, label: val.name });
                });
                this.activityArr = activity;
            })
            .catch(err => {});
        
    },
    watch: {
        'paramList': {
            handler: function (newVal,old) {
                newVal.forEach((val,i)=>{
                    if(JSON.stringify(val) != JSON.stringify(this.paramListCopy[i])){
                        val.isChange = true
                    }
                })
            },
            deep: true
        }
    },
    methods: {
        //获取商品信息
        getGoodsByRelation(){
            this.$fetch.post(getGoodsByRelation,{
                data:{
                    relation: this.$route.params.id
                }
            }).then(res=>{
                let common = Object.assign({},res.data[0]) ;
                this.form = common
                if(common.hotSale === 1){
                    this.hotSaleStatus = true
                }
                this.goodsItemCountVal = res.data.length
                let paramList = JSON.parse(JSON.stringify(res.data))
                paramList.forEach(val=>{
                    val.checked = false
                    console.log(val,'----val----')
                    if(val.goodsImageUrl == '' || val.goodsImageUrl == null){
                        val.goodsImageUrl =[]
                    }else{
                        val.goodsImageUrl = val.goodsImageUrl.split(',')
                    }
                    val.soldoutStatus = val.soldout === 0 ? true : false;
                })
                this.paramList = paramList
                this.paramListCopy = JSON.parse(JSON.stringify(paramList))
                this.activityStatus = res.data[0].activityStatus;
            })
        },
        handleChange(val){
          
           
            if(val.checked){
                val.goodsSku = 'setEmpty'
            }else{
                this.getGoodsByRelation()
            }
            
        },
        hotSaleChange(val){
            if(val){
                this.form.presaleTime = new Date(`${new Date().getFullYear()}-
                        ${new Date().getMonth() + 1}
                        ${new Date().getDate()} 20:30:00`);
            }
        },
        // 商品款数变化
        goodsItemCountChange(val){
            this.paramList = []
            for (let i = 0; i < val; i++) {
                this.addgoodsItem()
            }
        },
        //获取活动列表
        getActivity() {
            let params = {
                data: {
                    id: "" + this.form.activityId,
                    storeNo: this.user.storeNo
                }
            };
            this.$fetch.post(getActivityDetail, params).then(res => {
                this.activityStatus = res.data.status;
            });
        },
        clickImage(index) {
            this.imageNum = index;
            this.isShow1 = true;
        },
        closeImage() {
            this.isShow1 = false;
        },
        // 会员折扣率变动
        changeMemberRate() {
            let { memberRate, discountPrice, memberPrice } = this.form;
            if (memberRate && discountPrice) {
                this.form.memberPrice =
                    Math.round(discountPrice * memberRate) / 10;
            }
        },
        // 会员价变化
        changeMemberPrice() {
            let { memberRate, discountPrice, memberPrice } = this.form;
            if (+memberPrice > +discountPrice) {
                this.$message({
                    message: "会员折扣价不能大于商品折扣价",
                    type: "warning",
                    duration: 1500
                });
            } else if (memberPrice && discountPrice) {
                this.form.memberRate =
                    Math.round(memberPrice / discountPrice * 100) / 10;
            }
        },
        // 折扣价变动
        changeDiscountPrice() {
            this.form.discountRate = "";
            if (
                this.form.goodsPrice &&
                this.form.goodsPrice != "" &&
                this.form.discountPrice &&
                this.form.discountPrice != ""
            ) {
                this.form.discountRate =
                    Math.round(
                        (+this.form.discountPrice - +this.form.storePrice) *
                            100 /
                            +this.form.goodsPrice
                    ) / 10;
            }
            this.changeMemberPrice();
            this.changeMemberRate();
        },
        // 处理原价变动
        handleOrignailChange() {
            if (
                this.form.discountRate &&
                this.form.discountRate != "" &&
                this.form.goodsPrice &&
                this.form.goodsPrice != ""
            ) {
                this.form.discountPrice =
                    Math.round(
                        this.form.goodsPrice * this.form.discountRate / 10
                    );
            }
            this.changeMemberPrice();
            this.changeMemberRate();
        },
        //////////////////////////////
        // 单独定价折扣价变动
        setChangeDiscountPrice(idx) {
            this.paramList[idx].discountRate = "";
            if (
                this.paramList[idx].goodsPrice &&
                this.paramList[idx].goodsPrice != "" &&
                this.paramList[idx].discountPrice &&
                this.paramList[idx].discountPrice != ""
            ) {
                this.paramList[idx].discountRate =
                    Math.round((+this.paramList[idx].discountPrice) * 100 / +this.paramList[idx].goodsPrice) / 10;
            }
            this.setChangeMemberPrice(idx);
            this.setChangeMemberRate(idx);
        },
        // 单独定价处理原价变动
        setOrignailChange(idx) {
            if (
                this.paramList[idx].discountRate &&
                this.paramList[idx].discountRate != "" &&
                this.paramList[idx].goodsPrice &&
                this.paramList[idx].goodsPrice != ""
            ) {
                this.paramList[idx].discountPrice =
                    Math.round(
                        this.paramList[idx].goodsPrice * this.paramList[idx].discountRate / 10
                    ) ;
            }
            this.setChangeMemberPrice(idx);
            this.setChangeMemberRate(idx);
        },
        // 单独定价会员折扣率变动
        setChangeMemberRate(idx) {
            let { memberRate, discountPrice, memberPrice } = this.paramList[idx];
            if (memberRate && discountPrice) {
                this.paramList[idx].memberPrice =
                    Math.round(discountPrice * memberRate) / 10;
            }
        },
        // 单独定价会员价变化
        setChangeMemberPrice(idx) {
            let { memberRate, discountPrice, memberPrice } = this.paramList[idx];
            if (+memberPrice > +discountPrice) {
                this.$message({
                    message: "会员折扣价不能大于商品折扣价",
                    type: "warning",
                    duration: 1500
                });
            } else if (memberPrice && discountPrice) {
                this.paramList[idx].memberRate =
                    Math.round(memberPrice / discountPrice * 100) / 10;
            }
        },
        // 添加款数
        addgoodsItem(val) {
            this.paramListEdit.push({
                setPrice: false,
                goodsColor: "",
                goodsSku:'',//待加商品SKU码
                goodsImageUrl: [],
                discountPrice: "",
                discountRate: "",
                memberPrice: "",
                memberRate: 9,
                goodsStock: [
                    {
                        specsName: "S",
                        stockNum: "0",
                        barCode:''
                    }
                ]
            });
            if(val === 'other'){
                this.goodsItemCountVal = this.paramList.length 
            }
        },
        // 添加库存尺码
        addgoodsSize(idx) {
            console.log(this.paramList[idx].goodsStock,'add')
            this.paramList[idx].goodsStock.push({
                size: '',
                num: 0,
                barCode:''
            });
        },
        delgoodsSize(idx) {
            let leng = this.paramList[idx].goodsStock
            let j = 0;
            console.log(this.paramList[idx].goodsStock,'del')
            // this.paramList[idx].goodsStock.forEach((item,i) => {
            //     if(item.size == '' && item.barCode ==''){
            //         this.paramList[idx].goodsStock.splice(i,1)
            //         console.log(j++,'j')
            //     }
            //     return 
            // })
            for( let i = 0; i < leng.length; i++){
                if(leng[i].size == '' && leng[i].barCode == ''){
                    leng.splice(i,1)
                    break
                }
            }
        },
        // 删除颜色
        delColor(idx) {
            this.paramList.splice(idx, 1);
            this.goodsItemCountVal = this.paramList.length 
        },
        message(msg, icon) {
            this.$message({
                message: msg,
                type: icon ? icon : "error"
            });
        },
        submit() {
            let {
                goodsName,
                goodsPrice,
                storeNo,
                categoryId,
                goodsPic,
                soldout,
                brandId,
                goodsDesc,
                activityId,
                purchaseCost,
                storePrice,
                discountPrice,
                discountRate,
                memberPrice,
                memberRate,
                goodsCode,
                commonGoodsImg,
                sort,
                relation,
                usp
            } = this.form
            let filter,
                isAllow = true;
            if (goodsName.trim() === "") {
                this.message("商品名称不能为空");
            } else if (this.hotSaleStatus && (this.presaleTime === "" || this.presaleTime === 0)) {
                this.message("请输入爆款开始时间");
            }  else if (brandId === "") {
                this.message("选择商品品牌")
            } else if (activityId === "") {
                this.message("选择商品活动")
            } else if (String(goodsCode).trim() === "") {
                this.message("请输入商品编号")
            } else if (String(sort).trim() === '') {
                this.message("请输入排序")
            }else{
                let colors = [];
                for (let i = 0; i < this.paramList.length; i++) {
                    const val = this.paramList[i];
                    console.log(val,'parval')
                    if(val.discountPrice == '' || val.discountRate == '' || val.memberPrice == '' || val.memberRate == ''){
                        this.message(`请正确填写第${i + 1}个的价格信息`)
                        isAllow = false
                        break
                    }
                    if (colors.indexOf(val.goodsColor) >= 0) {
                        this.message(`商品规格重复！`)
                        isAllow = false
                        break
                    }else{
                        colors.push(val.goodsColor)
                    }
                    let filter = val.goodsStock.filter((size,s)=>{
                        
                        return String(size.specsName).trim() != '' && String(size.stockNum).trim() != '' 
                    })
                    let filterNum = val.goodsStock.filter(size => {
                        return !/^\d+$/g.test(size.stockNum) && size.stockNum != '' && size.specsName != 'null' && size.barCode != ''
                    })
                    let filterBarcode =  val.goodsStock.filter(size => {
                        console.log(size.stockNum,'stockNum')
                        return ((!/^[-\_A-Za-z0-9]+$/g.test(size.barCode) && size.barCode != '')  || size.barCode == '') && size.specsName != undefined && size.specsName != null && size.stockNum != null && size.stockNum != ''
                    })
                    if(filter.length === 0){
                        console.log(filter,'filter')
                        isAllow = false
                        this.message(`第${i + 1}个商品的库存不能为空`)
                        break
                    }else{
                        console.log(filter,'filter')
                        val.goodsSize = []
                        filter.forEach(s => {
                            val.goodsSize.push({
                                num: +s.stockNum,
                                size: s.specsName,
                                barCode:s.barCode
                            })
                        });
                    }
                    console.log(filterNum,'filterNum')
                    if(filterNum.length > 0){
                        this.message(`第${i + 1}个商品的库存请填写数字`)
                        isAllow = false
                        break
                    }
                    if(filterBarcode.length > 0){
                        this.message(`第${i + 1}个商品的条码不能含有中文字符,且不为空`)
                        isAllow = false
                        break
                    }
                    if(val.goodsColor === ''){
                        this.message(`请填写第${i + 1}个商品规格`)
                        isAllow = false
                        break
                    }
                    console.log(val,'----valval----')
                    if(val.goodsSku === ''){
                        this.message(`请填写第${i + 1}个商品sku`)
                        isAllow = false
                        break
                    }
                    if(val.goodsImageUrl.length + commonGoodsImg > 9){
                        this.message(`第${i + 1}个商品图片超过限制！`)
                        isAllow = false
                        break
                    }
                    val.goodsSize.forEach((item,i)=>{
                        console.log(item,'----item')
                        if(item.size == undefined || item.barCode == '' || !Number(item.num)){
                            this.message(`第${i + 1}个商品尺码库存条形码不符合要求`)
                            isAllow = false
                        }
                    })
                    if(val.goodsSku === ''){
                        this.message(`请填写第${i + 1}个商品sku`)
                        isAllow = false
                        break
                    }
                }
                if(isAllow){
                    // 更新修改了的规格
                    let needUpdate = []
                    this.paramList.forEach((val,i)=>{
                        if(val.isChange){
                            needUpdate.push(val)
                        }
                    })
                    this.$confirm("确认提交？").then(_ => {
                        let newParams = []
                        needUpdate.forEach(val=>{
                            console.log(val,'---====val')
                            if(val.checked){
                                val.goodsSku = 'setEmpty'
                            }
                           console.log(val,'---====val++++')
                            let {goodsId,goodsPrice,goodsColor,discountPrice,discountRate,memberPrice,memberRate,goodsImageUrl,goodsSize,soldoutStatus,goodsSku} = val
                            newParams.push({
                                goodsId: goodsId,
                                goodsPrice: '' + goodsPrice,
                                discountPrice: '' + discountPrice,
                                discountRate: '' + discountRate,
                                memberPrice: '' + memberPrice,
                                memberRate: '' + memberRate,
                                goodsImg: goodsImageUrl,
                                goodsSize: goodsSize,
                                soldout: soldoutStatus ? 0 : 1,
                                goodsPic: goodsImageUrl[0],
                                goodsColor,
                                goodsSku:goodsSku
                            })
                        })
                        console.log(newParams,'newParams')
                        let params = {
                            data:{
                                goodsName,
                                relation,
                                brandId: +brandId,
                                goodsDesc,
                                activityId: '' + activityId,
                                storeNo: this.user.storeNo,
                                // styleCount: newParams.length,
                                paramList: newParams,
                                sort,
                                usp,
                                categoryId: '0',
                                hotSale: 0,
                                goodsCode
                            }
                        }
                        if (this.hotSaleStatus) {
                            params.data.hotSale = 1;
                            params.data.presaleTime = +new Date(
                                this.form.presaleTime
                            ).getTime();
                        }
                        this.$fetch.post(updateRelationGoods,params)
                            .then(res=>{
                                this.message(res.message,'success')
                                setTimeout(() => {
                                    this.$router.go(-1);
                                }, 1500);
                            })
                            .catch(err => {
                                this.message(err.message);
                            });
                    })
                }
            }
        },
        hideSel(e) {
            let className = e.target.className;
            if (
                className.search("selList") < 0 &&
                className.search("selGoodsItem") < 0 &&
                className.search("gray") < 0
            ) {
                this.isShowGoodsItem = false;
            }
        },
        // // 多级项目选择
        selGoodsItem(res) {
            this.isShowGoodsItem = true;
            this.goodsItem2 = [];
            this.goodsItem3 = [];
            this.goodsItem = [];
        },
        loadTwo(val, name) {
            this.goodsItem = [];
            this.goodsItem.push({
                val: val,
                name: name
            });
            this.$fetch
                .get(getCategory + "?categoryId=" + val)
                .then(res => {
                    this.goodsItem2 = res.data;
                })
                .catch(err => {
                    this.message(err.message, "error");
                });
        },
        loadTree(val, name) {
            this.$fetch
                .get(getCategory + "?categoryId=" + val)
                .then(res => {
                    this.goodsItem[1] = {
                        val: val,
                        name: name
                    };
                    this.goodsItem3 = res.data;
                })
                .catch(err => {
                    this.message(err.message, "error");
                });
        },
        selDone(val, name) {
            this.goodsItem[2] = {
                val: val,
                name: name
            };
            this.isShowGoodsItem = false;
        },
        //限制图片750*750
        upload(idx, e) {
            const that = this;
            var files = e.target.files;
            for (let i = 0; i < files.length; i++) {
                let width, height;
                // let reader = new FileReader();
                // reader.onload = function(e) {
                //     var image = new Image();
                //     image.onload = function() {
                //         width = image.width;
                //         height = image.height;
                //         if (width >= 400 && height >= 400 && width == height) {
                        if(files[i].size / 1000 <= 400){
                            that.uploadLoading = true;
                            that.$http
                                .get(getQiniuToken, {
                                    params: {
                                        wxUid: "",
                                        wxSid: ""
                                    }
                                })
                                .then(res1 => {
                                    let config = {
                                        headers: {
                                            "Content-Type":
                                                "multipart/form-data"
                                        }
                                    };
                                    let formdata = new FormData(); //创建form对象
                                    formdata.append(
                                        "file",
                                        files[i],
                                        files[i].name
                                    );
                                    formdata.append("chunk", "0"); //断点传输
                                    formdata.append("chunks", "1");
                                    formdata.append("token", res1.data.uptoken);
                                    // http://goods.dingdian.xin 图片上传地址
                                    that.$http.post("http://up-z1.qiniup.com", formdata, config).then(res2 => {
                                        if (res2.data.key != "" && i < 9) {
                                            // 加判断是第几个商品
                                            that.paramList[
                                                idx
                                            ].goodsImageUrl.push(
                                                qiniuBaseUrl +
                                                    res2.data.key +
                                                    "?imageMogr2/thumbnail/300000@"
                                            );
                                            that.paramList[
                                                idx
                                            ].goodsImageUrl = that.paramList[
                                                idx
                                            ].goodsImageUrl.slice(0, 9);
                                            that.$message({
                                                title: "提示",
                                                message: "图片上传成功",
                                                type: "success",
                                                duration: 1500
                                            });
                                        }
                                        that.uploadLoading = false;
                                    });
                                });
                            }else{
                                that.$message.warning(`上传图片大于400KB`)
                            }
                //         } else {
                //             that.$message({
                //                 title: "提示",
                //                 message: "上传图片尺寸要求不小于400*400方图",
                //                 type: "warning"
                //             });
                //         }
                //     };
                //     image.src = e.target.result;
                // };
                // reader.readAsDataURL(files[i]);
            }
        },
        // 删除公共图片
        deleteCommonImgList(form,id){
            form.commonGoodsImg.splice(id, 1);
        },
        // 删除不同款式的图片
        deleteImgList(idx, id) {
            idx.goodsImageUrl.splice(id, 1);
        },
        goToPrev(item, idx) {
            let newImg = item.goodsImageUrl.slice();
            if (idx > 0) {
                let now = newImg[idx].toString();
                let prev = newImg[idx - 1].toString();
                newImg[idx] = prev;
                newImg[idx - 1] = now;
            }
            item.goodsImageUrl = newImg;
        }
    }
};
</script>

<style scoped lang="less">
@import url("../../style/activity.less");
@import url("../../style/goods.less");
.activity-right {
    h3 {
        margin-bottom: 20px;
    }
}
.formLeft,.formRight{
    display: inline-block
}

.setPrice{
    // display: flex;
    width: 80%;
    & > div{
        display: inline-block;
    }
}
.stock {
    display: inline-block;
    margin-top: -10px;
    margin-left: -10px;;
    li {
        float: left;
        margin: 10px;
        
        input {
            width: 40px;
        }
    }
}
.addGoods-1 {
    margin-top: 20px;
    border-bottom: 2px solid #000;
}
.addColor {
    margin-bottom: 10px;
    margin-left: 80%;
}
.submit {
    margin-left: 0;
    margin-top: 50px;
}
.form {
    margin-bottom: 20px;
    border-bottom: 2px solid #000;
}
</style>